package com.iedu.demo.lgq.service.impl;

import com.iedu.demo.lgq.entity.*;
import com.iedu.demo.lgq.mapper.OrderMapper;
import com.iedu.demo.lgq.mapper.OrderItemMapper;
import com.iedu.demo.lgq.mapper.TbKuaidi100DeliveryMapper;
import com.iedu.demo.lgq.mapper.UserMapper;
import com.iedu.demo.lgq.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Date;

@Service

public class OrderServiceImpl implements OrderService {

    @Autowired
    private TbKuaidi100DeliveryMapper tbKuaidi100DeliveryMapper;

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private UserMapper userMapper;

    @Transactional
    @Override
    public TbOrder createOrder(String userName, List<TbOrderItem> items, String payment, Integer paymentType, String postFee, String buyerMessage, TbUserAddress userAddress) {
     // 根据用户名查找用户
        TbUser user = userMapper.findById(userName);  // 调用userService查找用户
        if (user == null) {
            throw new RuntimeException("用户不存在");  // 如果用户不存在，抛出异常
        }

        TbOrder order = new TbOrder();
        order.setUserId(user.getId());  // 设置订单的 userId（使用查询到的 userId）
        order.setPayment(payment);
        order.setPaymentType(paymentType);
        order.setPostFee(postFee);
        order.setBuyerMessage(buyerMessage);
        order.setStatus(1);  // 默认未付款状态
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());

        // 保存订单到数据库
        orderMapper.saveOrder(order);  // 通过 orderMapper 调用保存方法
      // 确保订单的 ID 已经生成，并赋值给订单项
        Integer orderId = order.getOrderId();  // 获取生成的 orderId
        if (orderId == null) {
            throw new RuntimeException("订单ID生成失败");
        }
        // 保存订单项
        for (TbOrderItem item : items) {
            item.setOrderId(order.getOrderId());  // 设置订单ID
            orderItemMapper.saveOrderItem(item);  // 通过 orderItemMapper 调用保存方法
        }

        return order;  // 返回创建的订单
    }

    @Override
    public String applyRefund(Integer orderId, Integer refundStatus, String refundReason) {
        //查找订单
        TbOrder order = orderMapper.findOrderById(orderId);
        // 检查订单是否存在，并且订单状态为已完成(status == 5)
        if (order != null && order.getStatus() == 5) { // 5: 交易成功
            // 更新退款状态为已申请 (refundStatus = 1)
            int result = orderMapper.updateRefundStatus(orderId, refundStatus, refundReason);

            // 检查是否更新成功
            if (result > 0) {
                return "Refund request submitted!";
            }
            return "Refund request failed!";
        }

        return "Refund request failed! Order is not eligible for refund.";
    }

    // 商家处理退款
    @Override
    public String processRefund(Integer orderId) {
        // 查找订单
        TbOrder order = orderMapper.findOrderById(orderId);

        // 检查订单是否存在，并且订单的退款状态是否为已申请 (refundStatus == 1)
        if (order != null && order.getRefundStatus() == 1) { // 1: 已申请退款
            // 设置退款状态为已处理 (refundStatus = 2)
            int result = orderMapper.updateRefundStatus(orderId, 2, null); // 商家处理退款时，退款理由可以为空

            if (result > 0) {
                return "Refund processed successfully!";
            }
            return "Refund processing failed!";
        }

        return "Refund processing failed! Order is not eligible for processing.";
    }

    @Override
    public String shipOrder(Integer orderId) {
        TbOrder order = orderMapper.findOrderById(orderId);
        if(order == null){
            return "order not found";
        }
        if (order != null && order.getStatus() == 3) { // : 3为待发货状态
            order.setStatus(4); // 4：已发货
            order.setConsignTime(new Date());//记录发货时间

            //更新订单状态
            orderMapper.updateOrderStatus(orderId,4);
            return "Order shipped successfully!";
        }
        return"Order cannot be shipped";

    }
    @Override
    public List<Kuaidi100Delivery> getAllDeliveryCompanies () {
        return tbKuaidi100DeliveryMapper.findAllDeliveryCompanies();
    }

    @Override
    public String selectDeliveryCompany(Integer orderId, long deliveryId, String trackingNumber){
        TbOrder order = orderMapper.findOrderById(orderId);
        if (order != null) {
            // 获取快递公司名称
            String deliveryName = tbKuaidi100DeliveryMapper.findDeliveryNameById(deliveryId);
            if (deliveryName == null) {
                return "Delivery company not found!";
            }
            // 更新订单的快递公司信息
            order.setShippingCode(trackingNumber); // 设置物流单号
            order.setShippingName(deliveryName); // 获取快递公司名称
            // 更新订单状态为待发货（status = 3）
            if (order.getStatus() != 3) { // 只有当订单状态不是待发货时才更新
                order.setStatus(3); // 设置订单为待发货
            }
            orderMapper.updateOrderForDelivery(order);//更新订单信息
            return "Delivery company selected successfully!";
        }
        return "Order not found!";
    }


        @Override
        public List<TbOrder> getOrders ( int page, int pageSize, Integer status, Integer userId, Integer orderId){
            return orderMapper.findOrders(page, pageSize, status, userId, orderId);
        }

        @Override
        public TbOrder getOrderById (Integer orderId){
            return orderMapper.findOrderById(orderId);
        }

        @Override
        public boolean updateOrderStatus(Integer orderId, Integer status){
            int rows = orderMapper.updateOrderStatus(orderId, status);
            return rows > 0;
        }

        @Override
        public boolean updateRefundStatus (Integer orderId, Integer refundStatus, String refundReason){
            int rows = orderMapper.updateRefundStatus(orderId, refundStatus, refundReason);
            return rows > 0;
        }

        @Override
    public String getRefundStatus(Integer orderId) {
        TbOrder order = orderMapper.findOrderById(orderId);
        if (order == null) {
            return "Order not found!";
        }
        switch ((int) order.getRefundStatus()) {
            case 0:
                return "Refund not applied";//未申请退款
            case 1:
                return "Refund requested";//退款已请求
            case 2:
                return "Refund processed";//退款已处理
            default:
                return "Unknown refund status";//未知
        }
    }



        @Override
        @Transactional
        public void deleteOrders (List < String > orderIds) {
            // 删除订单商品
            orderItemMapper.deleteOrderItemsByOrderIds(orderIds);
            // 删除订单
            orderMapper.deleteOrders(orderIds);
        }

        @Override

        /**
         * 处理支付请求，更新订单状态
         * @param orderId 订单ID
         * @return 返回支付处理结果
         */
        public boolean processPayment (Integer orderId) {
            // 获取订单
            TbOrder order = orderMapper.findOrderById(orderId);
            if (order == null) {
                return false;  // 订单不存在
            }

            // 获取订单状态并进行空值检查
            Integer status = order.getStatus();
            if (status == null || status != 1) {
                return false;// 状态为 null 或不是 1，表示订单已支付或已取消，不能再次支付

            }
            // 假设支付成功，更新订单状态和支付时间
            Date paymentTime = new Date();  // 当前时间作为支付时间
            int updated = orderMapper.updateOrderPayment(orderId, 2, paymentTime);  // 更新订单状态和支付时间

            return updated > 0;  // 判断是否更新成功

        }
        // 实现 updateOrderPayment 方法
        @Override
        public int updateOrderPayment(Integer orderId, Integer status, Date paymentTime) {
            // 调用Mapper的方法进行数据库更新
            int result = orderMapper.updateOrderPayment(orderId, status, paymentTime);
            System.out.println("更新的行数: " + result);  // 输出影响的行数
            return result;
        }
}

